<template>
  <!-- #ifdef MP-WEIXIN -->
  <button 
    class="login-btn" 
    open-type="getPhoneNumber" 
    @getphonenumber="onGetPhoneNumber" 
    @click="WXLogin"
  >
    一键登录
  </button>
  <!-- #endif -->
</template>

<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/userdata'

const API_BASE_URL = 'https://yinlihupo.cn'
const userStore = useUserStore()
const loading = ref(false)
const code = ref('')

const emit = defineEmits(['loginSuccess'])

const WXLogin = async () => {
  loading.value = true
  console.log('[关键节点] 开始微信一键登录')
  
  try {
    const loginRes = await uni.login({
      provider: 'weixin'
    })
    
    if (!loginRes.code) {
      throw new Error('获取微信登录code失败')
    }
    
    code.value = loginRes.code
    console.log('[关键节点] 获取到微信登录code:', code.value)
  } catch (err) {
    console.error('[关键节点] 获取微信登录code失败:', err)
    loading.value = false
    uni.showToast({ 
      title: '登录失败，请重试', 
      icon: 'none' 
    })
  }
}

const onGetPhoneNumber = async (e) => {
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    uni.showToast({ title: '获取手机号失败', icon: 'none' })
    loading.value = false
    return
  }

  try {
    const { encryptedData, iv } = e.detail
    
    const res = await uni.request({
      url: `${API_BASE_URL}/account/wechat/login/`,
      method: 'POST',
      data: {
        code: code.value,
        encryptedData,
        iv,
        device_id: uni.getSystemInfoSync().deviceId
      },
      header: {
        'content-type': 'application/json'
      }
    })

    if (res.data && res.data.user_id) {
      console.log('[关键节点] 微信一键登录成功', {
        user_id: res.data.user_id,
        phone: res.data.phone,
        time: new Date().toISOString()
      })
      
      userStore.setUserInfo({
        id: res.data.user_id,
        phone: res.data.phone,
        nickname: res.data.nickname,
        access_token: res.data.access,
        refresh_token: res.data.refresh,
        is_wechat_bound: true
      })
      
      uni.showToast({ title: '登录成功' })
      emit('loginSuccess')
    } else {
      throw new Error(res.data.message || '登录失败')
    }
  } catch (err) {
    console.error('[关键节点] 微信一键登录失败:', err)
    uni.showToast({ 
      title: err.message || '登录失败', 
      icon: 'none' 
    })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-btn {
  margin: 40rpx 30rpx 0;
  color: white;
  border: none;
  border-radius: 40rpx;
  padding: 24rpx 0;
  font-size: 32rpx;
  box-shadow: 0 0 10px rgba(56, 182, 255, 0.2);
  transition: all 0.3s ease;
  background-color: #0b405e;
}

.login-btn:active {
  transform: scale(0.96);
  box-shadow: 0 0 5px rgba(56, 182, 255, 0.3);
}
</style>
